package com.neuedu.android.helloworld.my;

import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.neuedu.android.helloworld.R;
import com.neuedu.android.helloworld.common.CommonResult;
import com.neuedu.android.helloworld.entity.Passanger;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class TicketBuy3ChooiceConcat extends AppCompatActivity {

    ListView lvChooicePassanger;
    Button addPassanger;
    List data = new ArrayList();
    ArrayList<Passanger> selectPassanger = new ArrayList();
    private MyListViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ticket_buy3_chooice_concat);
        addPassanger = findViewById(android.R.id.button1);
        lvChooicePassanger = findViewById(R.id.lvChooicePassanger);
        addPassanger.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //回传结果  TicketBuy3ChooiceConcat 999
                Intent intent = new Intent();
                intent.putExtra("passanger", selectPassanger);
                setResult(999, intent);
                //结束当前Activity
                finish();
            }
        });

        initData();

        adapter = new MyListViewAdapter(data);
        //给listView设置适配器
        lvChooicePassanger.setAdapter(adapter);

    }

    private void initData() {
//        Random rnd = new Random();
//        for (int i = 0; i < 10; i++) {
//            //idCard, String type, String telphone
//            data.add(new Passanger(i, "乘客" + i, rnd.nextLong() + "", "成人", rnd.nextLong() + ""));
//        }

        //打开Dialog
//        new Thread
//        Handler

        new GetPassangerListTask().execute();


    }


    ProgressDialog dialog;

    class GetPassangerListTask extends AsyncTask<String ,Object ,CommonResult>{

//        onPreExecute、onPostExecute 在UI线程中执行


        /**
         * 启动任务的时候执行，比如打开加载 loading
         */
        @Override
        protected void onPreExecute() {
            //在开始网络请求之前 打开loading
            dialog = ProgressDialog.show(TicketBuy3ChooiceConcat.this, "", "加载中，请稍后",
                    true,
                    false);
        }

        @Override
        protected void onPostExecute(CommonResult commonResult) {

            if(dialog != null){
                dialog.dismiss();
            }

            System.out.println(commonResult);
            System.out.println(commonResult);
            System.out.println(commonResult);
            //更新ListView（联系人列表）
            List<Passanger> list = commonResult.getObj();
            data.clear();
            data.addAll(list);
            adapter.notifyDataSetChanged();//更新ListVIew
        }

        //在子线程中调用 调用网络请求
        @Override
        protected CommonResult  doInBackground(String... strings) {
            String api = "http://www.fulfill.com.cn:3146/android-server/passanger/list";
            URL url = null;
            try {
                url = new URL(api);
                URLConnection urlConnection = url.openConnection();
                InputStream is = urlConnection.getInputStream();
                Gson gson = new GsonBuilder().create();
                CommonResult result = gson.fromJson(new InputStreamReader(is), CommonResult.class);

                return result;
            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }


//        @Override
//        protected Object doInBackground(Object[] objects) {
//            //用于发起网络请求
//            return null;
//        }
//
//        @Override
//        protected void onPostExecute(Object o) {
//            super.onPostExecute(o);
//        }

    }







    class MyListViewAdapter extends BaseAdapter {

        private List myData;

        public MyListViewAdapter(List myData) {
            this.myData = myData;
        }

        @Override
        public int getCount() {
            return myData == null ? 0 : myData.size();
        }

        @Override
        public Object getItem(int position) {
            return myData == null ? null : myData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v;
            ViewHolder viewHolder;
            //没有缓存过
            if (convertView == null) {
                //使用xml渲染
                v = getLayoutInflater().inflate(R.layout.activity_ticket_buy3__chooice_list_item, parent, false);
                viewHolder = new ViewHolder();
                viewHolder.cbSelectPassanger = v.findViewById(R.id.cbSelectPassanger);
                viewHolder.tvName = v.findViewById(R.id.tvName);
                viewHolder.tvIdCard = v.findViewById(R.id.tvIdCard);
                viewHolder.tvTel = v.findViewById(R.id.tvTel);
                v.setTag(viewHolder);
            } else {
                v = convertView;
                viewHolder = (ViewHolder) v.getTag();
            }


            Passanger passanger = (Passanger) getItem(position);


            viewHolder.tvName.setText(passanger.getName()+"("+passanger.getType()+")");
            viewHolder.tvIdCard.setText(passanger.getIdCard());
            viewHolder.tvTel.setText(passanger.getTelphone());
            viewHolder.cbSelectPassanger.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(viewHolder.cbSelectPassanger.isChecked()){
//                        选中的乘客信息passanger
                        selectPassanger.add(passanger);
                    }else{
                        selectPassanger.remove(passanger);
                    }
                }
            });
            return v;
        }

        class ViewHolder {
            CheckBox cbSelectPassanger ;
            TextView tvName ;
            TextView tvIdCard ;
            TextView tvTel ;
        }
    }


}